const http = require("http");
const fs = require("fs");
const path = require("path");

http.createServer(function(req,res){
    var filename = process.argv[2];
    var dirPath = __dirname;

    fs.readdir(dirPath,(err,files)=>{
        if(err){
            console.log("文件目录读取失败!")
        }
        else{
            if(filename == null){
                var filePath1 = path.join(__dirname,"/fileReader1.js");
                var readable1 = fs.createReadStream(filePath1);
    
                readable1.pipe(res);
            }else{
                fs.access("./"+filename,(err)=>{
                    if(err){
                        console.log("文件不存在!")
                    }
                    else{
                        var filePath = path.join(__dirname,"/"+filename);
                        fs.readFile(filePath,(err,data)=>{
                            if(err){
                                console.log(err)
                            }else{
                                var readable = fs.createReadStream(filePath);
                                // res向客户端响应数据
                                readable.pipe(res);
                        
                            }
                        })
    
                    }
                })
            }
        }
    })
}).listen(8081);
console.log("server is listening 8081");